package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

func init() {
	//log.SetPrefix("TRACE: ")
	log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
}

type Book struct {
	Id        int
	Title     string
	CoverUrl  string
	Category  string
	Tags      string
	Author    string
	SourceUrl string
	Summary   string

	Chapters *[]Chapter

	Site *Site
}

type Chapter struct {
	Id        int
	BookId    int
	Title     string
	SortNo    int
	ParentId  int
	Content   string
	SourceUrl string

	Children *[]Chapter
	Book     *Book
}
type Site struct {
	Host    string `json:"host"`
	ItemUrl string `json:"itemUrl"`
	PageUrl string `json:"pageUrl"`
	Code    string `json:"code"`
	Slugs   string `json:"slugs"`
}

type CmdOption struct {
	BookId        string `json:"bookId"`
	Target        string `json:"target"`
	SiteName      string `json:"siteName"`
	Site          *Site  `json:"site"`
	CacheProvider string `json:"cacheProvider"`
	StartPage     int    `json:"startPage"`
	EndPage       int    `json:"endPage"`
}

func contains(arr []string, el string) bool {
	for _, v := range arr {
		if el == v {
			return true
		}
	}
	return false
}
func (co *CmdOption) parseHost() {
	if co.SiteName == "h" || co.SiteName == "hetushu" {
		co.Site = &Site{
			Code:    "hetushu",
			ItemUrl: "http://www.hetushu.com/book/%s/index.html",
			PageUrl: "http://www.hetushu.com/book/index.php?page=%d&state=2",
			Slugs:   "hetushu,h,",
		}
	} else if co.SiteName == "9" || co.SiteName == "99lib" {
		co.Site = &Site{
			Code:    "99lib",
			ItemUrl: "http://www.99lib.net/book/%s/index.htm",
			PageUrl: "",
			Slugs:   "99lib,9,",
		}
	} else {

	}
}
func (co *CmdOption) ComposeUrl() ([]string, bool) {
	if co.Site == nil {
		co.parseHost()
	}
	pageMode := false
	urlList := []string{}
	if co.BookId != "" {
		idList := strings.Split(co.BookId, ",")
		if len(idList) != 0 {
			for _, id := range idList {
				if id != "" {
					url := fmt.Sprintf(co.Site.ItemUrl, id)
					if !contains(urlList, url) {
						urlList = append(urlList, url)
					}
				}
			}
		}
	}
	if len(urlList) > 0 {
		pageMode = false
	} else {
		pageMode = true

		for i := co.StartPage; i <= co.EndPage; i++ {
			urlList = append(urlList, fmt.Sprintf(co.Site.PageUrl, i))
		}
	}

	return urlList, pageMode
}
func jsonEncode(i interface{}) string {
	data, _ := json.Marshal(i)
	return string(data)
}
func urlGet(url string) string {
	res, err := http.Get(url)
	defer res.Body.Close()
	if err != nil {
		log.Println(err)
		return ""
	}
	body, _ := ioutil.ReadAll(res.Body)
	//a, _ := Get("Hello")
	//log.Printf(a)
	return string(body)
}
func parseCmdOption() CmdOption {
	bookId := flag.String("book_id", "", "Book Id(s) separte by comma when have multiple")
	siteName := flag.String("site_name", "h", "Site Name: hetushu[h],99lib[9] ")
	target := flag.String("target", "epub2", "Target: epub2,epub3,db,txt ")
	cacheProvider := flag.String("cache", "local", "Cache Provider: local, memory, file, dummy")
	startPage := flag.Int("start", 0, "Start Page")
	endPage := flag.Int("end", 0, "End Page")
	flag.Parse()

	co := CmdOption{
		BookId:        *bookId,
		Target:        *target,
		SiteName:      *siteName,
		CacheProvider: *cacheProvider,
		StartPage:     *startPage,
		EndPage:       *endPage,
	}
	return co
}
func parseBook(book *Book) *Book {
	return nil
}
func parsePage(url string) []Book {
	return nil
}
func parseChapter(chapter *Chapter) *Chapter {
	return nil
}
func main() {
	co := parseCmdOption()

	log.Println(jsonEncode(co))
	urls, pageMode := co.ComposeUrl()
	if pageMode {
		for _, url := range urls {
			books := parsePage(url)
			for _, book := range books {
				parseBook(&book)
			}
		}
	} else {
		for _, url := range urls {
			book := &Book{}
			book.SourceUrl = url
			book.Site = co.Site

			parseBook(book)
		}
	}
}
